package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.TMajorPlan;
import com.ruoyi.system.domain.VApplicationInfoScore;
import com.ruoyi.system.service.ITMajorPlanService;
import com.ruoyi.system.service.IVApplicationInfoScoreService;
import com.ruoyi.system.util.PersonMerger;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.VSumApplicationResult;
import com.ruoyi.system.service.IVSumApplicationResultService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 考生成绩汇总Controller
 * 
 * @author ruoyi
 * @date 2024-12-15
 */
@Controller
@RequestMapping("/system/VSumApplicationResult")
public class VSumApplicationResultController extends BaseController
{
    private String prefix = "system/VSumApplicationResult";

    @Autowired
    private IVSumApplicationResultService vSumApplicationResultService;
    @Autowired
    private IVApplicationInfoScoreService ivApplicationInfoScoreService;

    @Autowired
    private ITMajorPlanService itMajorPlanService;


    @RequiresPermissions("system:VSumApplicationResult:view")
    @GetMapping()
    public String VSumApplicationResult()
    {
        return prefix + "/VSumApplicationResult";
    }

    /**
     * 查询考生成绩汇总列表
     */
    @RequiresPermissions("system:VSumApplicationResult:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(VSumApplicationResult vSumApplicationResult)
    {
        startPage();
        List<VSumApplicationResult> list = vSumApplicationResultService.selectVSumApplicationResultList(vSumApplicationResult);
        return getDataTable(list);
    }

    /**
     * 导出考生成绩汇总列表
     */
    @RequiresPermissions("system:VSumApplicationResult:export")
    @Log(title = "考生成绩汇总", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(VSumApplicationResult vSumApplicationResult)
    {
        List<VSumApplicationResult> list = vSumApplicationResultService.selectVSumApplicationResultList(vSumApplicationResult);
        ExcelUtil<VSumApplicationResult> util = new ExcelUtil<VSumApplicationResult>(VSumApplicationResult.class);
        return util.exportExcel(list, "考生成绩汇总数据");
    }

    /**
     * 新增考生成绩汇总
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存考生成绩汇总
     */
    @RequiresPermissions("system:VSumApplicationResult:add")
    @Log(title = "考生成绩汇总", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(VSumApplicationResult vSumApplicationResult)
    {
        return toAjax(vSumApplicationResultService.insertVSumApplicationResult(vSumApplicationResult));
    }

    /**
     * 修改考生成绩汇总
     */
    @RequiresPermissions("system:VSumApplicationResult:edit")
    @GetMapping("/edit/{name}")
    public String edit(@PathVariable("name") String name, ModelMap mmap)
    {
        VSumApplicationResult vSumApplicationResult = vSumApplicationResultService.selectVSumApplicationResultByName(name);
        mmap.put("vSumApplicationResult", vSumApplicationResult);
        return prefix + "/edit";
    }

    /**
     * 修改保存考生成绩汇总
     */
    @RequiresPermissions("system:VSumApplicationResult:edit")
    @Log(title = "考生成绩汇总", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(VSumApplicationResult vSumApplicationResult)
    {
        return toAjax(vSumApplicationResultService.updateVSumApplicationResult(vSumApplicationResult));
    }

    /**
     * 删除考生成绩汇总
     */
    @RequiresPermissions("system:VSumApplicationResult:remove")
    @Log(title = "考生成绩汇总", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(vSumApplicationResultService.deleteVSumApplicationResultByNames(ids));
    }

    /**
     * 查询汇总详细
     */
    @RequiresPermissions("system:VSumApplicationResult:list")
    @GetMapping("/detail/{examId}/{detalType}")
    public String detail(@PathVariable("examId") String examId,@PathVariable("detalType") String detalType, ModelMap mmap)
    {
        mmap.put("examId", examId);
        mmap.put("subjectType", detalType);
        return "system/VApplicationInfoScore/VApplicationInfoScore";
    }

    /**
     * 查询公告详细
     */
    @RequiresPermissions("system:notice:list")
    @GetMapping("/view/{idCardNumber}")
    public String view(@PathVariable("idCardNumber") String idCardNumber, ModelMap mmap) throws IllegalAccessException {
        VApplicationInfoScore vApplicationInfoScore = new VApplicationInfoScore();
        vApplicationInfoScore.setIdCardNumber(idCardNumber);
        List<VApplicationInfoScore> vApplicationInfoScoreList = ivApplicationInfoScoreService.selectVApplicationInfoScoreList(vApplicationInfoScore);
        mmap.put("vApplicationInfoScoreList", vApplicationInfoScoreList);
        VApplicationInfoScore vApplicationInfoScoreDto = PersonMerger.mergePersons(vApplicationInfoScoreList);
        mmap.put("vApplicationInfoScoreDto", vApplicationInfoScoreDto);
        TMajorPlan tMajorPlan = new TMajorPlan();
        tMajorPlan.setMajorName(vApplicationInfoScoreDto.getMajorName());
        List<TMajorPlan> tMajorPlans = itMajorPlanService.selectTMajorPlanList(tMajorPlan);
        mmap.put("tMajorPlans", tMajorPlans);
        mmap.put("vApplicationInfoScoreList", vApplicationInfoScoreList);
        VSumApplicationResult vSumApplicationResult = new VSumApplicationResult();
        compyteScoreByMMajorNames(tMajorPlans,vApplicationInfoScoreList);
        vSumApplicationResult.setIdCardNumber(idCardNumber);
        List<VSumApplicationResult> list = vSumApplicationResultService.selectVSumApplicationResultList(vSumApplicationResult);
        mmap.addAttribute("tasks", list);
        return prefix + "/view";
    }

    private List<TMajorPlan> compyteScoreByMMajorNames(List<TMajorPlan> tMajorPlans, List<VApplicationInfoScore> vApplicationInfoScoreList){

        for (TMajorPlan plan : tMajorPlans) {
            Optional<VApplicationInfoScore> newMatchingScore = getMatchingScores(vApplicationInfoScoreList,plan.getNewSubjectName());
            if (newMatchingScore.isPresent()) {
                VApplicationInfoScore score = newMatchingScore.get();
                    plan.setOldCredits(score.getScore()); // 更新旧学分
                    plan.setNewCredits("合格"); // 新学科默认合格
            } else {
                if(plan.getOldSubjectName().isEmpty() || "****".equals(plan.getOldSubjectName())){
                    continue;
                }
                Optional<VApplicationInfoScore> elsenewMatchingScore = getMatchingScores(vApplicationInfoScoreList,plan.getOldSubjectName());
                if (elsenewMatchingScore.isPresent()) {
                    VApplicationInfoScore score = elsenewMatchingScore.get();
                    plan.setNewCredits(score.getScore()); // 更新成绩
                    plan.setOldCredits("合格"); // 旧学科默认合格
                }
            }
        }
        List<TMajorPlan> updatedPlans = tMajorPlans.stream()
                .filter(plan -> StringUtils.isEmpty(plan.getNewCredits()) || StringUtils.isEmpty(plan.getOldCredits()))
                .peek(personplan -> { // 使用peek而不是map，因为我们不改变流的元素类型，只是有副作用
                    personplan.setNewCredits("待考");
                    personplan.setOldCredits("无");
                })
                .collect(Collectors.toList()); // 收集结果

        // 如果您想更新原始的tMajorPlans变量，请确保它是可重新赋值的（例如，它不是final的）
        // tMajorPlans = updatedPlans; // 取消注释以更新原始变量

        return updatedPlans; // 返回更新后的列表
    }

    private Optional<VApplicationInfoScore> getMatchingScores(List<VApplicationInfoScore> vApplicationInfoScoreList,String subjectName){
        List<VApplicationInfoScore> matchingScores = vApplicationInfoScoreList.stream()
                .filter(score -> subjectName.equals(score.getSubjectName()))
                .collect(Collectors.toList());
        if (matchingScores.size() > 1) {
            throw new ServiceException("科目:" + subjectName + "找到多条数据，详细请到考生信息查询模块查看，并更正基础数据");
        }
        return matchingScores.size() > 0 ? matchingScores.stream().findFirst() : Optional.empty();

    }
}
